package org.john.springbootadmin.module.service.system.impl;

import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.john.springbootadmin.module.dao.system.SysRoleDao;
import org.john.springbootadmin.module.entity.system.SysRole;
import org.john.springbootadmin.module.service.system.SysRolePermissionService;
import org.john.springbootadmin.module.service.system.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import com.design.framework.base.service.impl.BaseServiceImpl;

/**
 * 系统角色管理
 * 
 * @author johnDeng
 * @dateTime 2019-03-18 02:09:25
 */
@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, Integer> implements SysRoleService {
	@Resource
	private SysRoleDao sysRoleDao;
	@Resource
	private SysRolePermissionService sysRolePermissionService;

	@PostConstruct
	public void initialize() {
		super.setBaseDao(sysRoleDao);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int insert(SysRole entity) {
		sysRoleDao.insert(entity);
		sysRolePermissionService.addSysRolePermission(entity.getPermissionIds(), entity.getId());
		return 1;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int deleteBatchById(List<SysRole> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			sysRolePermissionService.deleteBatchByRoleId(list);
		}
		return sysRoleDao.deleteBatchById(list);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public int update(SysRole entity) {
		if (CollectionUtils.isNotEmpty(entity.getPermissionIds())) {
			// 先删除中间表，再添加
			sysRolePermissionService.deleteBatchByRoleId(Arrays.asList(entity));
			sysRolePermissionService.addSysRolePermission(entity.getPermissionIds(), entity.getId());
		}
		return sysRoleDao.update(entity);
	}

}
